﻿using Confluent.Kafka;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace MQHelper.Kafka
{
    public class KafkaConsumer : IDisposable
    {
        private bool disposedValue;
        private IConsumer<Null, string> _consumer;
        private IEnumerable<KeyValuePair<string, string>> _cnf;
        private List<string> _subscribeTopic;
        private bool _stopConsume;
        private System.Threading.CancellationTokenSource _cancellationSource;

        public string ClientName { get; private set; }
        public Action<Message<Null, string>> ReceivedAction { get; set; }

        public KafkaConsumer(string host, string groupId, List<string> subscribeTopic, uint commitInterval = 5000)
        {
            _cnf = new Dictionary<string, string>
            {
              { "group.id", groupId },
              { "bootstrap.servers", host },
              { "auto.commit.interval.ms", commitInterval.ToString() },
              { "auto.offset.reset", "earliest" }
            };
            _subscribeTopic = subscribeTopic;
        }

        public void Start()
        {
            ConsumerBuilder<Null, string> builder = new ConsumerBuilder<Null, string>(_cnf);
            _consumer = builder.Build();
            ClientName = _consumer.Name;
            _consumer.Subscribe(_subscribeTopic);
            _cancellationSource = new System.Threading.CancellationTokenSource();
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    if (_stopConsume) { break; }
                    ConsumeResult<Null, string> rs = _consumer.Consume(_cancellationSource.Token);
                    ReceivedAction.Invoke(rs.Message);
                }
            });
            _consumer.Consume();
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: 释放托管状态(托管对象)
                    _stopConsume = true;
                    _cancellationSource.Cancel();
                    _consumer.Dispose();
                }
                // TODO: 释放未托管的资源(未托管的对象)并重写终结器
                // TODO: 将大型字段设置为 null
                disposedValue = true;
            }
        }

        // // TODO: 仅当“Dispose(bool disposing)”拥有用于释放未托管资源的代码时才替代终结器
        // ~KafkaConsumer()
        // {
        //     // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中
        //     Dispose(disposing: false);
        // }

        public void Dispose()
        {
            // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中
            Dispose(disposing: true);
            GC.SuppressFinalize(this);
        }
    }
}